<template>
	<view class="ai-container">
		<view v-if="chatList.length == 0" class="no-chat-wrapper">
			<view class="ai-header">
				<view class="ai-logo">
					<image src="@/static/ai.png" mode="scaleToFill" />
				</view>
				<view class="ai-title">Hi！我是捉友AI助手</view>
				<view class="ai-subtitle">让我来帮你解答桌游相关的问题吧</view>
			</view>
			<view class="ai-ask-title">你可以这样问我：</view>
			<!-- 预设问题 -->
			<view class="ai-ask-list">
				<view v-for="item in tipQuestionList" :key="item" class="ai-ask-item" @click="handleTipQuestion(item)">
					{{ item.content }}
					<u-icon name="arrow-right" :color="themeColor" size="16"></u-icon>
				</view>
			</view>
		</view>

		<view v-else class="chat-wrapper">
			<view v-for="item in chatList" :key="item" class="chat-item">
				<view v-if="item.role == 'user'" class="user-chat">
					<view class="user-chat-content">{{ item.content }}</view>
					<image :src="userInfo.avatarUrl" class="user-chat-avatar" />
				</view>
				<view v-else class="ai-chat">
					<view v-if="item.loading == true" class="ai-chat-content">
						正在思考中...<u-loading-icon mode="semicircle" timing-function="ease" inactive-color="#2b6de5"></u-loading-icon>
					</view>
					<view v-if="item.loading == false && item.content" v-html="markText(item.content)" class="ai-chat-content"></view>
					<view v-if="item.loading == false && !item.content" class="ai-chat-content"> 网络异常，请刷新重试！ </view>
				</view>
			</view>

			<!-- 清除对话 悬浮按钮 -->
			<view class="clear-chat-btn" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd" @click="handleClearChat">
				<image src="@/static/clear.png" />
			</view>
		</view>

		<view class="input-wrapper">
			<u-textarea v-model="chatValue" :maxlength="-1" autoHeight placeholder="请输入内容"></u-textarea>
			<image src="@/static/send.png" class="send-btn" @click="handleSend" />
		</view>

		<!-- Tabbar -->
		<Tabbar :active="1"></Tabbar>
	</view>
</template>

<script>
import request from '@/api/http.js';
import { marked } from 'marked';

export default {
	data() {
		return {
			chatValue: '',
			chatList: [],
			tipQuestionList: [
				{
					content: '推荐适合新手玩的桌游',
					icon: ''
				},
				{
					content: 'UNO桌游的玩法是什么',
					icon: ''
				},
				{
					content: '推荐几个适合2人的桌游',
					icon: ''
				},
				{
					content: '《卡卡颂》的规则是什么',
					icon: ''
				}
			],
			userInfo: {
				avatarUrl: '',
				nickName: '',
				sex: ''
			},
			loading: false,
			marked: require('marked'),
			position: { x: 50, y: 50 }, // 初始位置
			startX: 0, // 开始触摸的X坐标
			startY: 0, // 开始触摸的Y坐标
			isDragging: false // 是否正在拖拽
		};
	},
	onLoad() {
		this.handleGetUserData();
	},
	mounted() {
		this.handleGetChatList();
	},
	methods: {
		async handleGetChatList() {
			const res = await request(`/chat/list`);
			let chatList = [];
			for (let i = 0; i < res.data.length; i++) {
				chatList.push({
					role: 'user',
					content: res.data[i].question
				});
				// 判断是否是其他问题
				chatList.push({
					role: 'assistant',
					content: res.data[i].answer,
					loading: false
				});
			}
			this.chatList = chatList;
		},
		async handleGetUserData() {
			const res = await request(`/user/getUserData?openid=${uni.getStorageSync('openid')}`);
			let userInfo = res.data;
			userInfo.open = userInfo.open === 1 ? true : false;
			userInfo.sex = userInfo.sex === 0 ? '男' : '女';
			this.userInfo = userInfo;
		},
		async handleSend() {
			if (!this.chatValue || this.loading) return;
			this.chatList.push({ role: 'user', content: this.chatValue });
			this.chatList.push({ role: 'assistant', content: '正在思考中...', loading: true, others: false });
			this.loading = true;
			let chat = this.chatValue;
			this.chatValue = '';
			// 发送请求
			let res = await request(`/chat/chat`, { question: chat }, 'POST');
			this.chatList[this.chatList.length - 1].loading = false;
			this.loading = false;
			// 处理回调信息
			console.log(res);
			this.chatList[this.chatList.length - 1].content = res.data.answer;
		},
		handleTipQuestion(tip) {
			this.chatValue = tip.content;
		},
		markText(text) {
			return this.marked(text);
		},
		toRoute(route) {
			uni.navigateTo({
				url: '/pages/route/route?id=' + route.id
			});
		},
		async handleClearChat() {
			const res = await request(`/chat/delete`);
			if (res.code == 200) {
				this.chatList = [];
				uni.showToast({title: '清除成功！', icon: 'none'})
			} else {
				uni.showToast({title: '网络错误！', icon: 'none'})
			}
		},
		onTouchStart(event) {
			this.startX = event.touches[0].pageX; // 获取触摸开始时的X坐标
			this.startY = event.touches[0].pageY; // 获取触摸开始时的Y坐标
			this.isDragging = true; // 开始拖拽标记为true
		},
		onTouchMove(event) {
			if (this.isDragging) {
				// 如果正在拖拽，则更新位置
				const moveX = event.touches[0].pageX - this.startX; // 计算移动的X距离
				const moveY = event.touches[0].pageY - this.startY; // 计算移动的Y距离
				this.position.x += moveX; // 更新X坐标位置
				this.position.y += moveY; // 更新Y坐标位置
				this.startX = event.touches[0].pageX; // 更新开始触摸的X坐标为当前位置，以便下一次计算移动距离时使用当前位置作为起始点。
				this.startY = event.touches[0].pageY; // 同上，更新Y坐标。
			}
		},
		onTouchEnd() {
			this.isDragging = false; // 拖拽结束，标记为false。
		}
	}
};
</script>

<style lang="scss">
page {
	background-color: #f8f8f8;
}

.ai-container {
	padding: 20rpx;

	.no-chat-wrapper {
		.ai-header {
			display: flex;
			flex-direction: column;
			align-items: center;
			text-align: center;
			gap: 20rpx;
			margin-bottom: 100rpx;

			.ai-logo {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 150rpx;
				height: 150rpx;
				border-radius: 100%;
				background-color: $theme-color;

				image {
					width: 96rpx;
					height: 96rpx;
				}
			}

			.ai-title {
				font-size: 48rpx;
				color: #333;
				font-weight: bold;
			}

			.ai-subtitle {
				font-size: 28rpx;
				color: #666;
			}
		}

		.ai-ask-title {
			font-size: 28rpx;
			color: #666;
			margin-top: 40rpx;
			margin-bottom: 50rpx;
		}

		.ai-ask-list {
			display: flex;
			align-items: center;
			flex-direction: column;
			gap: 20rpx;

			.ai-ask-item {
				width: 500rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				background-color: #fff;
				border-radius: 25rpx;
				padding: 40rpx;
				box-shadow: 0 3px 9px #eee;
				font-size: $font-size-base;
				color: #333;

				image {
					width: 40rpx;
					min-width: 40rpx;
					height: 40rpx;
					margin-right: 20rpx;
				}

				&:active {
					background-color: #fcfcfc;
				}
			}
		}
	}

	.input-wrapper {
		position: fixed;
		bottom: 128rpx;
		left: 0;
		right: 0;
		padding: 20rpx;
		background-color: #fff;
		box-shadow: 0 -3px 9px #eee;
		border-radius: 25rpx 25rpx 0 0;
		z-index: 10;
		width: calc(100% - 40rpx);
		min-height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.u-textarea {
			width: 100%;
			min-height: 1.1rem;
			max-height: 600rpx;
			overflow-y: scroll;
			background-color: #f5f5f5;
			border-radius: 50rpx;
			padding: 20rpx 40rpx;
			border: none;
			font-size: 28rpx;
			color: #333;
		}

		.send-btn {
			width: 40rpx;
			height: 40rpx;
			color: #fff;
			font-size: 28rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-left: 20rpx;
		}
	}

	.chat-wrapper {
		padding-bottom: 200rpx;
		display: flex;
		flex-direction: column;

		.chat-item {
			margin-bottom: 40rpx;

			.user-chat {
				display: flex;
				justify-content: flex-end;

				&-avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 100%;
					overflow: hidden;
					margin-right: 20rpx;
					flex-shrink: 0;
				}

				&-content {
					padding: 20rpx;
					background-color: #fff;
					border-radius: 25rpx;
					box-shadow: 0 3px 9px #eee;
					font-size: 28rpx;
					text-align: justify;
					color: #333;
					max-width: 70%;
					border-top-right-radius: 0;
					margin: 0 20rpx;
					text-wrap: wrap;
					overflow: hidden;
				}
			}

			.ai-chat {
				display: flex;

				&-content {
					display: flex;
					padding: 20rpx;
					font-size: 28rpx;
					color: #333;
				}

				.u-loading-icon {
					margin-left: 40rpx;
				}

				.route-button {
					width: 300rpx;
					border-radius: 25rpx;
					overflow: hidden;
					padding: 20rpx;
					background-color: $theme-color;
					color: #fff;
					font-size: 28rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					&:active {
						background-color: $theme-color-dark;
					}
				}
			}
		}

		.clear-chat-btn {
			position: fixed;
			bottom: 500rpx;
			right: 20rpx;
			width: 80rpx;
			height: 80rpx;
			border-radius: 100%;
			background-color: $theme-color;
			box-shadow: 0 3px 9px #ccc;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			color: #666;
			z-index: 20;

			&:active {
				background-color: #dc7004;
			}

			image {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}
}

.no-chat-wrapper {
	padding-bottom: 200rpx;
}
</style>
